using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Rock : MonoBehaviour
{
    public int HP;
    public GameObject HurtNumber;
    private Renderer render;
    public GameObject itemDrop;
    private Animator anim;
    private Collider2D coll;
    private int HurtNum;
    private bool stillAlive=true;
    // Start is called before the first frame update
    void Start()
    {
        render = GetComponent<SpriteRenderer>();
        anim = GetComponent<Animator>();
        coll = GetComponent<Collider2D>();
    }
    void Update()
    {
        if (HP <= 0 && stillAlive)
        {
            stillAlive = false;
            anim.SetBool("isdead", true);
            coll.enabled = false;
            for(int i = 1; i <= 10; i++)
            {
                float a = Random.Range(-100, 100);
                float b = Random.Range(-50, 50);
                GameObject instance = GameObject.Instantiate(itemDrop, new Vector3(
                    transform.position.x + a / 100, transform.position.y + b / 100, transform.position.z), transform.rotation);
            }
        }
    }
    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.gameObject.layer == LayerMask.NameToLayer("Bullet_Player") || collision.gameObject.layer == LayerMask.NameToLayer("Knife"))
        {
            if (collision.GetComponent<bullet>() != null)
            { HurtNum = collision.GetComponent<bullet>().damage; }
            if (collision.GetComponent<bullet2>() != null)
            { HurtNum = collision.GetComponent<bullet2>().damage; }
            Vector3 vector = new Vector2((float)UnityEngine.Random.Range(-20, 20) / 100, (float)UnityEngine.Random.Range(100, 140) / 100);
            GameObject gb = Instantiate(HurtNumber, transform.position + vector, transform.rotation);
            gb.GetComponent<TextMesh>().text = HurtNum.ToString();
            HP -= HurtNum;
            render.material.color = Color.red;
            Invoke("ReColor", 0.05f);
        }
    }
    void ReColor()
    {
        render.material.color = Color.white;
    }
}
